package cc.rengu.igas.bomp.core.service.trans;

import cc.rengu.igas.bomp.common.constant.TableNameConstant;
import cc.rengu.igas.bomp.common.dao.BizTmpMapper;
import cc.rengu.igas.bomp.common.dao.MchntBaseInfoMapper;
import cc.rengu.igas.bomp.common.dao.MchntImageInfoMapper;
import cc.rengu.igas.bomp.common.dao.MchntSignInfoMapper;
import cc.rengu.igas.bomp.common.dao.impl.BizTmpMapperImpl;
import cc.rengu.igas.bomp.common.dao.impl.MchntBaseInfoMapperImpl;
import cc.rengu.igas.bomp.common.dao.impl.MchntImageInfoMapperImpl;
import cc.rengu.igas.bomp.common.dao.impl.MchntSignInfoMapperImpl;
import cc.rengu.igas.bomp.common.entity.BizTmp;
import cc.rengu.igas.bomp.common.entity.MchntBaseInfo;
import cc.rengu.igas.bomp.common.entity.MchntImageInfo;
import cc.rengu.igas.bomp.common.entity.MchntSignInfo;
import cc.rengu.igas.bomp.common.enums.QueryBizTypeEnum;
import cc.rengu.igas.bomp.common.enums.RespCodeEnum;
import cc.rengu.igas.bomp.common.util.InitParamUtil;
import cc.rengu.igas.bomp.core.service.base.ManageService;
import cc.rengu.igas.bomp.facade.bean.ImageInfoBean;
import cc.rengu.igas.bomp.facade.bean.MchntImageInfoBean;
import cc.rengu.igas.bomp.facade.request.MchntImageInfoQueryRequest;
import cc.rengu.igas.bomp.facade.response.MchntImageInfoQueryResponse;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.utility.util.BeanUtil;
import cc.rengu.oltp.utility.util.ConvertUtil;
import cc.rengu.oltp.utility.util.StringUtil;
import com.alibaba.fastjson.JSON;
import org.apache.commons.codec.binary.Base64;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 商户影像信息查询
 * Created by 赵奎伍
 */
public class MchntImageInfoQueryService extends ManageService {

    @Override
    protected Object bizBeforeCust() throws Exception {
        MchntImageInfoQueryRequest mchntImageInfoQueryRequest = new MchntImageInfoQueryRequest();
        ConvertUtil.convertOutput(mchntImageInfoQueryRequest);
        return mchntImageInfoQueryRequest;
    }

    @Override
    protected BizResponse bizProcessCust(Object request) throws Exception {
        MchntImageInfoQueryRequest mchntImageInfoQueryRequest = (MchntImageInfoQueryRequest) request;
        MchntImageInfoQueryResponse mchntImageInfoQueryResponse = new MchntImageInfoQueryResponse();
        BizResponse<MchntImageInfoQueryResponse> bizResponse = new BizResponse<>();
        bizResponse.setRspSysId(AppParamConstant.SYS_ID);
        BeanUtil.beanCopy(mchntImageInfoQueryRequest, mchntImageInfoQueryResponse);

        String bizType = mchntImageInfoQueryRequest.getHeader().getBizType();
        if (StringUtil.isEmptyOrNull(bizType)) {
            rglog.error("bizType<{}>为NULL!,无法查询信息", bizType);
            bizResponse.setRespCode(RespCodeEnum.PARAM_ERROR.getRespCode());
            bizResponse.setRespDesc(RespCodeEnum.PARAM_ERROR.getRespDesc());
            bizResponse.setResult(mchntImageInfoQueryResponse);
            return bizResponse;
        }

        /*查询商户基本信息表 */
        MchntBaseInfoMapper mchntBaseInfoMapper = new MchntBaseInfoMapperImpl();
        MchntBaseInfo mchntBaseInfo = mchntBaseInfoMapper.selectMchntBaseInfoByPrimaryKey(mchntImageInfoQueryRequest.getHeader().getInstId(), mchntImageInfoQueryRequest.getMchntNo());

        if (QueryBizTypeEnum.QUERY_TEMPORARY_TABLE.getType().equals(bizType)) {
            /* 查询临时表数据 */
            BizTmpMapper bizTmpMapper = new BizTmpMapperImpl();
            List<BizTmp> bizTmpList = bizTmpMapper.selectBizTmpByMchntNo(mchntImageInfoQueryRequest.getHeader().getInstId(), mchntImageInfoQueryRequest.getMchntNo(), TableNameConstant.T_B_MCHNT_IMAGE_INFO);

            if (!CollectionUtils.isEmpty(bizTmpList)) {
                /* 赋值imageInfoBeans */
                Map<String, MchntImageInfoBean> map = new HashMap<>();
                for (BizTmp bizTmp : bizTmpList) {
                    String mchntImageInfoJson = InitParamUtil.getJsonString(bizTmp);
                    MchntImageInfo mchntImageInfo = JSON.parseObject(mchntImageInfoJson, MchntImageInfo.class);
                    String key = mchntImageInfo.getImageType();
                    if (map.containsKey(key)) {
                        MchntImageInfoBean mchntImageInfoBean = map.get(key);
                        convImageInfo(mchntImageInfo, mchntImageInfoBean.getImageInfoList());
                    } else {
                        MchntImageInfoBean mchntImageInfoBean = new MchntImageInfoBean();
                        mchntImageInfoBean.setImageType(mchntImageInfo.getImageType());
                        List<ImageInfoBean> imageInfoBeans = new ArrayList<>();
                        convImageInfo(mchntImageInfo, imageInfoBeans);
                        if (!CollectionUtils.isEmpty(imageInfoBeans)) {
                            mchntImageInfoBean.setImageInfoList(imageInfoBeans);
                            map.put(key, mchntImageInfoBean);
                        }
                    }
                }

                List<MchntImageInfoBean> mchntImageInfoBeans = new ArrayList<>(map.values());

                /* 查询结果赋值 */
                mchntImageInfoQueryResponse.setMchntImageInfoList(mchntImageInfoBeans);
                mchntImageInfoQueryResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
                mchntImageInfoQueryResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
                /* 按照接口转换基础产品信息并响应给请求方 */
                bizResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
                bizResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());

                List<BizTmp> signBizTmpList = bizTmpMapper.selectBizTmpByMchntNo(mchntImageInfoQueryRequest.getHeader().getInstId(), mchntImageInfoQueryRequest.getMchntNo(), TableNameConstant.T_B_MCHNT_SIGN_INFO);

                if (!CollectionUtils.isEmpty(signBizTmpList)) {
                    /* 赋值imageInfoBeans */
                    String mchntSignInfoJson = InitParamUtil.getJsonString(signBizTmpList.get(0));
                    MchntSignInfo mchntSignInfo = JSON.parseObject(mchntSignInfoJson, MchntSignInfo.class);

                    mchntImageInfoQueryResponse.setMchntSignId(mchntSignInfo.getMchntSignId());
                }
            } else {
                getMchntImageInfoByFormalTable(mchntImageInfoQueryRequest, mchntImageInfoQueryResponse, bizResponse, mchntBaseInfo);
            }

        } else {
            rglog.error("根据条件查询商户图片信息临时表查询为空!，查询正式表数据");
            getMchntImageInfoByFormalTable(mchntImageInfoQueryRequest, mchntImageInfoQueryResponse, bizResponse, mchntBaseInfo);
        }


        if (null != mchntBaseInfo) {
            mchntImageInfoQueryResponse.setAuditStatus(mchntBaseInfo.getAuditStatus());
            mchntImageInfoQueryResponse.setAuditRefuseReason(mchntBaseInfo.getAuditRefuseReason());
            mchntImageInfoQueryResponse.setLastOprId(mchntBaseInfo.getLastOprId());
            mchntImageInfoQueryResponse.setLastUpdateTime(mchntBaseInfo.getLastUpdateTime());
        }

        bizResponse.setResult(mchntImageInfoQueryResponse);
        return bizResponse;
    }

    private void getMchntImageInfoByFormalTable(MchntImageInfoQueryRequest mchntImageInfoQueryRequest, MchntImageInfoQueryResponse mchntImageInfoQueryResponse, BizResponse<MchntImageInfoQueryResponse> bizResponse, MchntBaseInfo mchntBaseInfo) throws Exception {
        /* 查询商户影像信息表 */
        MchntImageInfoMapper mchntImageInfoMapper = new MchntImageInfoMapperImpl();
        List<MchntImageInfo> mchntImageInfos = mchntImageInfoMapper.selectMchntImageInfoByMchntNo(mchntImageInfoQueryRequest.getHeader().getInstId(), mchntImageInfoQueryRequest.getMchntNo());
        if (null != mchntImageInfos && !mchntImageInfos.isEmpty()) {
            /* 按照创建时间降序排序 */
            List<MchntImageInfo> mchntImageInfoList = mchntImageInfos.stream().filter(item -> AppParamConstant.YES.equals(item.getRecordStatus())).sorted(Comparator.comparing(MchntImageInfo::getCreateTime)).collect(Collectors.toList());
            Collections.reverse(mchntImageInfoList);

            if (!CollectionUtils.isEmpty(mchntImageInfoList)) {
                /* 赋值imageInfoBeans */
                Map<String, MchntImageInfoBean> map = new HashMap<>();
                for (MchntImageInfo mchntImageInfo : mchntImageInfoList) {
                    String key = mchntImageInfo.getImageType();
                    if (map.containsKey(key)) {
                        MchntImageInfoBean mchntImageInfoBean = map.get(key);
                        convImageInfo(mchntImageInfo, mchntImageInfoBean.getImageInfoList());
                    } else {
                        MchntImageInfoBean mchntImageInfoBean = new MchntImageInfoBean();
                        mchntImageInfoBean.setImageType(mchntImageInfo.getImageType());
                        List<ImageInfoBean> imageInfoBeans = new ArrayList<>();
                        convImageInfo(mchntImageInfo, imageInfoBeans);
                        mchntImageInfoBean.setImageInfoList(imageInfoBeans);
                        map.put(key, mchntImageInfoBean);
                    }
                }
                List<MchntImageInfoBean> mchntImageInfoBeans = new ArrayList<>(map.values());

                /* 查询结果赋值 */
                mchntImageInfoQueryResponse.setMchntImageInfoList(mchntImageInfoBeans);
            }
            mchntImageInfoQueryResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
            mchntImageInfoQueryResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
            /* 按照接口转换基础产品信息并响应给请求方 */
            bizResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
            bizResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        } else {
            rglog.error("商户<{}>无商户影像信息!", mchntImageInfoQueryRequest.getMchntNo());
            bizResponse.setRespCode(RespCodeEnum.QUERY_DATA_IS_NULL.getRespCode());
            bizResponse.setRespDesc(RespCodeEnum.QUERY_DATA_IS_NULL.getRespDesc());
            bizResponse.setResult(mchntImageInfoQueryResponse);
        }

        MchntSignInfoMapper mchntSignInfoMapper = new MchntSignInfoMapperImpl();
        MchntSignInfo mchntSignInfo = mchntSignInfoMapper.selectMchntSignInfoByPrimaryKey(mchntImageInfoQueryRequest.getHeader().getInstId(), mchntBaseInfo.getMchntNo());
        mchntImageInfoQueryResponse.setMchntSignId(mchntSignInfo.getMchntSignId());
    }

    @Override
    protected void bizAfterCust(Object response) throws Exception {
        BizResponse bizResponse = (BizResponse) response;
        MchntImageInfoQueryResponse mchntImageInfoQueryResponse = (MchntImageInfoQueryResponse) bizResponse.getResult();
        ConvertUtil.convertInput(mchntImageInfoQueryResponse);
    }

    /**
     * 将数据库表结构对象转换成接口对象
     *
     * @param mchntImageInfo      数据库表结构对象
     * @param mchntImageInfoBeans 接口对象
     */
    private void convMchntImageInfo(MchntImageInfo mchntImageInfo, List<MchntImageInfoBean> mchntImageInfoBeans, List<ImageInfoBean> imageInfoBeans) {
        MchntImageInfoBean mchntImageInfoBean = new MchntImageInfoBean();
        BeanUtil.beanCopy(mchntImageInfo, mchntImageInfoBean);
        mchntImageInfoBean.setImageInfoList(imageInfoBeans);
        mchntImageInfoBeans.add(mchntImageInfoBean);
    }

    /**
     * 将数据库表结构对象转换成接口对象
     *
     * @param mchntImageInfo 数据库表结构对象
     * @param imageInfoBeans 接口对象
     */
    private void convImageInfo(MchntImageInfo mchntImageInfo, List<ImageInfoBean> imageInfoBeans) {
        ImageInfoBean imageInfoBean = new ImageInfoBean();
        if (null != mchntImageInfo) {
            if (AppParamConstant.NO.equals(mchntImageInfo.getRecordStatus())) {
                rglog.debug("已删除影像数据<{}>,不返回", mchntImageInfo.getId());
                return;
            }
            BeanUtil.beanCopy(mchntImageInfo, imageInfoBean);
            imageInfoBean.setId(mchntImageInfo.getId());
            imageInfoBean.setImageId(mchntImageInfo.getImageId());
            imageInfoBean.setWechatImageId(mchntImageInfo.getWechatMediaId());
            imageInfoBean.setAlipayImageId(mchntImageInfo.getAlipayImageId());
            if (!StringUtil.isEmptyOrNull(mchntImageInfo.getImageRemotePath())) {
                imageInfoBean.setImagePath(Base64.encodeBase64String(mchntImageInfo.getImageRemotePath().getBytes()));//todo 是哪个路径 本地、远程、缩略图
            }

            if (!StringUtil.isEmptyOrNull(mchntImageInfo.getImageLocalPath())) {
                imageInfoBean.setImageLocalPath(Base64.encodeBase64String(mchntImageInfo.getImageLocalPath().getBytes()));
            }
            imageInfoBeans.add(imageInfoBean);
        }
    }
}
